package log

import (
	"bytes"
	"fmt"
	"github.com/sirupsen/logrus"
	"os"
	"time"
)

const FormatTimeLayout = "2006-01-02 15:04"

const (
	CBlack = iota
	CRed
	CGreen
	CYellow
	CBlue
	CPurple
	CCyan
	CGray
)

type FileDateHook struct {
	file     *os.File
	logPath  string
	fileDate string
	appName  string
}

func (h *FileDateHook) Levels() []logrus.Level {
	return logrus.AllLevels
}

func (h *FileDateHook) Fire(entry *logrus.Entry) error {
	if entry.Time.Format(FormatTimeLayout) != h.fileDate {
		h.fileDate = entry.Time.Format(FormatTimeLayout)
		h.file.Close()
		h.CreateFile()
	}
	line, _ := entry.String()
	h.file.Write([]byte(line))
	return nil
}

func (h *FileDateHook) CreateFile() {
	logPath := fmt.Sprintf("%s/%s", h.logPath, h.fileDate)
	_, err := os.Stat(logPath)
	if err != nil {
		err = os.MkdirAll(logPath, os.ModePerm)
		if err != nil {
			logrus.Errorln(err)
			return
		}
	}
	file, err := os.OpenFile(fmt.Sprintf("%s/%s_%s.log", logPath, h.appName, h.fileDate), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
	if err != nil {
		logrus.Errorln(err)
		return
	}
	h.file = file
}

type MyFormatter struct {
	Prefix     string
	TimeFormat string
}

func (f MyFormatter) Format(entry *logrus.Entry) ([]byte, error) {
	// 设置buffer缓冲区
	var b *bytes.Buffer
	if entry.Buffer == nil {
		b = &bytes.Buffer{}
	} else {
		b = entry.Buffer
	}
	// 设置格式
	fmt.Fprintf(b, "%s\n", entry.Message)
	return b.Bytes(), nil
}

func InitLogger(logRootPath, appName string) {
	fileDate := time.Now().Format(FormatTimeLayout)
	fileHook := FileDateHook{logPath: logRootPath, fileDate: fileDate, appName: appName}
	fileHook.CreateFile()
	logrus.AddHook(&fileHook)
	logrus.SetLevel(logrus.DebugLevel)
	logrus.SetReportCaller(true)
	logrus.SetFormatter(&MyFormatter{"GIN", time.DateTime})
}
